package com.interfaces;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.midi.MidiDevice.Info;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.common.web.CommonJspKeys;
import com.common.web.CommonKeys;
import com.common.web.Json;
import com.common.web.ReturnCodes;
import com.core.guarantee.GuaranteeJspKeys;
import com.core.guarantee.bo.GuaranteeBo;
import com.core.guarantee.dto.GuaranteeSearchCondition;
import com.core.guarantee.pojo.Guarantee;
import com.core.sendAgent.dto.SendAgentSearchCondition;
import com.core.user.bo.UserBo;
import com.core.user.pojo.User;
import com.core.visitor.bo.VisitorBo;
import com.core.visitor.dto.VisitorSearchCondition;
import com.core.visitor.pojo.Visitor;
import com.util.DataBaseUtil;
import com.util.ExceInputUtil;
import com.util.GsonUtil;
import com.util.UploadUtil;
import com.util.exception.ComRuntimeException;
import com.util.exception.ComSystemException;
import com.util.framework.BaseController;

@Controller
public class GuaranteeController extends BaseController{
	@Resource
	private GuaranteeBo guaranteeBo;
	@Resource
	private VisitorBo visitorBo;
	@Resource
	private UserBo userBo;
	@Resource
	private UploadUtil uploadUtil;
	@Resource
	private ExceInputUtil exceInputUtil;
	protected Logger log= Logger.getLogger(this.getClass());
	public static final String URL_ENTITY = "/guarantee";
	public static final String URL_ADD_UPDATE = URL_ENTITY + "/add_update";
	public static final String URL_UPDATE = URL_ENTITY + "/update";
	public static final String URL_DEL = URL_ENTITY + "/del";
	public static final String URL_DB_SEARCH = URL_ENTITY+"/search";
	public static final String URL_GOTO_MAIN_PAGE = URL_ENTITY + "/goto_main_page";
    public static final String URL_GOTO_ADD_UPDATE_PAGE = URL_ENTITY + "/goto_add_update_page";
    public static final String URL_GOTO_ADD_PAGE = URL_ENTITY + "/goto_add_page";
    public static final String URL_GOTO_UPDATE_PAGE = URL_ENTITY + "/goto_update_page";
    public static final String URL_UPDATESTATE=URL_ENTITY+"/updateState";
    public static final String URL_UPLOAD = URL_ENTITY+"/upload";
	@ResponseBody
	@RequestMapping(value=URL_DB_SEARCH,method=RequestMethod.POST,produces={"application/json;charset=utf-8"})
	public Object searchData(GuaranteeSearchCondition sc, HttpSession session){
		User userInfo =(User) session.getAttribute(CommonKeys.SESSION_USER);
		User userInfo2 =userBo.getById(userInfo);
		String msg="";
		sc.setAddTravelId(userInfo2.getTravelAgentId());
		List<Guarantee>data = guaranteeBo.getPojoList(sc,userInfo2);
		DataBaseUtil<Guarantee> db = new DataBaseUtil<Guarantee>();
		int totalCount = guaranteeBo.getPojoListCnt(sc,userInfo2);
		if (data.size()==0) {
			msg="{\"draw\":"+sc.getDraw()+",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
		}else{
			db.setTotalCount(totalCount);
			db.setRecordsFiltered(totalCount);
			db.setData(data);
			msg = GsonUtil.gson.toJson(db);
		}
		return msg;
	}
	@ResponseBody
	@RequestMapping(value = URL_ADD_UPDATE, method = RequestMethod.POST)
	public Json add(GuaranteeSearchCondition sc, HttpSession session) {
		Json json = new Json();
		Visitor visitor =new Visitor();
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		User userInfo2 =userBo.getById(userInfo);
		try {
			  sc.setAddDate(new Date());
			  sc.setAddUserId(userInfo2.getId().toString());
			  sc.setAddTravelId(userInfo2.getTravelAgentId());
			  sc.setIsVisa(0);
			  guaranteeBo.add(sc);
			  visitor.setName(sc.getFirstPersonName());
			  visitor.setPinyinName(sc.getPinyinName());
			  visitor.setVisaInfoId(sc.getId());
			  visitor.setIsLead("1");
			  visitorBo.add(visitor);
			  json.setNowId(sc.getId());
			  json.setSuccess(true);
			  json.setReturnCode(0);
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
					+ e.getMessage());
		}
		return json;
	}
	
	@ResponseBody
	@RequestMapping(value = URL_UPDATE, method = RequestMethod.POST,produces={"application/json;charset=utf-8"})
	public Json update(GuaranteeSearchCondition sc, HttpSession session) {
		Json json = new Json();
		Guarantee tempGuarantee=guaranteeBo.getById(sc);
		Visitor visitor =visitorBo.getFirstVisitor(sc.getId());
		try {
			
			if (tempGuarantee!=null) {
				visitor.setName(sc.getFirstPersonName());
				visitor.setPinyinName(sc.getPinyinName());
				guaranteeBo.update(sc);
				visitorBo.update(visitor);
				json.setSuccess(true);
				json.setReturnCode(0);
			}
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
					+ e.getMessage());
		}
		return json;
	}
	@ResponseBody
	@RequestMapping(value = URL_DEL, method = RequestMethod.POST,produces={"application/json;charset=utf-8"})
	public Json del(GuaranteeSearchCondition sc, HttpSession session,HttpServletRequest request) {
		String items = request.getParameter("delitems");
	    String[] strs = items.split(",");
		Json json = new Json();
		Guarantee tempGuarantee =new Guarantee();
		VisitorSearchCondition vsc =new VisitorSearchCondition();
		for (int i = 0; i < strs.length; i++) {  
			try {
				tempGuarantee.setId(Long.parseLong(strs[i]));
				vsc.setVisaInfoId(Long.parseLong(strs[i]));
				List<Visitor> visitorList =visitorBo.getVisitorList(vsc);
				guaranteeBo.del(tempGuarantee);
				for (Visitor visitor : visitorList) {
					visitorBo.del(visitor);
				}
				json.setSuccess(true);
			} catch (ComRuntimeException e) {
				json = new Json(e.getErrorCode(), e.getMessage());
			} catch (ComSystemException e) {
				log.error("error", e);
				json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
			} catch (Throwable e) {
				log.error("error", e);
				json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
						+ e.getMessage());
			}
		}
		return json;
	}
	@ResponseBody
	@RequestMapping(value = URL_UPDATESTATE, method = RequestMethod.POST)
	public Json updateState(HttpServletRequest request) {
		String items = request.getParameter("delitems");
		String afterState = request.getParameter("afterState");
	    String[] strs = items.split(",");
		Json json = new Json();
		Guarantee tempGuarantee =new Guarantee();
		for (int i = 0; i < strs.length; i++) {  
			try {
				tempGuarantee.setId(Long.parseLong(strs[i]));
				tempGuarantee.setState(afterState);
				guaranteeBo.updateState(tempGuarantee);
				json.setSuccess(true);
			} catch (ComRuntimeException e) {
				json = new Json(e.getErrorCode(), e.getMessage());
			} catch (ComSystemException e) {
				log.error("error", e);
				json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
			} catch (Throwable e) {
				log.error("error", e);
				json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
						+ e.getMessage());
			}
		}
		return json;
	}
	
//	文件上传
	@RequestMapping(value=URL_UPLOAD,method=RequestMethod.POST)
	@ResponseBody
	public String uploadFile(@RequestParam("file1") CommonsMultipartFile fileExcel,HttpServletRequest req,HttpServletResponse response,@RequestParam("txtId") String txtId)throws IOException{
		String road =uploadUtil.uploadFile(fileExcel, txtId);
		log.info(road);
//		String resString=exceInputUtil.inputExcelReturn(road);
		return road;
	}
	@RequestMapping(value=URL_GOTO_MAIN_PAGE,method=RequestMethod.GET)
	public ModelAndView gotoMainPage(HttpSession session,SendAgentSearchCondition sc) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		ModelAndView modelAndView= new ModelAndView("/guarantee/guarantee_main");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo,userInfo);
		return modelAndView;
	}

	@RequestMapping(value=URL_GOTO_ADD_UPDATE_PAGE,method=RequestMethod.GET)	
	public ModelAndView URL_GOTO_ADD_UPDATE_PAGE(HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		ModelAndView modelAndView = new ModelAndView("guarantee/guarantee_add");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
		return modelAndView;
	}
	
	@RequestMapping(value = URL_GOTO_UPDATE_PAGE, method = RequestMethod.GET)
	public ModelAndView URL_GOTO_UPDATE_PAGE(GuaranteeSearchCondition sc,HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		Guarantee sc1 = guaranteeBo.getById(sc);
		Visitor visitor = visitorBo.getFirstVisitor(sc.getId());
		sc1.setPinyinName(visitor.getPinyinName());
		sc1.setFirstPersonName(visitor.getName());
		ModelAndView modelAndView = new ModelAndView("guarantee/guarantee_update");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
		modelAndView.addObject(GuaranteeJspKeys.JspParam_Guarantee, sc1);
		return modelAndView;
	}
}
